<template>
  <upload-excel :on-success="success"></upload-excel>
</template>

<script>
import { importEmployees } from '@/api/employees'
export default {
  data() {
    return {
      type: this.$route.query.type
    }
  },
  methods: {
    success({ header, results }) {
      // 判断type 是否为 employees 是则为员工导入
      if (this.type === 'employees') {
        console.log('employees')
        this.importEmployee(results)
      }
      this.$router.back()
    },
    // 转化excel的日期格式
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    },
    // 批量导入员工
    async importEmployee(results) {
      const userRelations = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber'
      }
      /*  var arr = []
      results.forEach(item => {
        var userInfo = {}
        Object.keys(item).forEach(key => {
          userInfo[userRelations[key]] = item[key]
        })
        arr.push(userInfo)
      }) */
      var newArr = results.map(item => {
        var userInfo = {}
        Object.keys(item).forEach(key => {
          if (userRelations[key] === 'timeOfEntry' || userRelations[key] === 'correctionTime') {
            userInfo[userRelations[key]] = new Date(this.formatDate(item[key], '/'))
          } else {
            userInfo[userRelations[key]] = item[key]
          }
        })
        return userInfo
      })
      console.log(newArr)
      try {
        await importEmployees(newArr)
        console.log(1)
        this.$message.success('导入成功')
      } catch (error) {
        console.log('电话可能出现重复导致导入失败')
      }
    }
  }
}
</script>

<style scoped>
</style>
